package org.example.code.test2024.nine_mouth;

import java.util.HashMap;
import java.util.Map;

public class Trie {
    private final TrieNode root;

    public Trie() {

        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            node = node.children.computeIfAbsent(c, k -> new TrieNode());
        }
        node.isWord = true;
    }
    
    public boolean search(String word) {
        TrieNode node = getNode(word);
        return node!=null&&node.isWord;
    }
    
    public boolean startsWith(String prefix) {
        return getNode(prefix)!=null;
    }

    private TrieNode getNode(String prefix) {
        TrieNode node = root;
        for (char c : prefix.toCharArray()) {
            node = node.children.get(c);
            if (node == null) {
                return null;
            }
        }
        return node;
    }

}

class TrieNode{
    Map<Character, TrieNode> children;
    boolean isWord;
    public TrieNode() {
        isWord = false;
        this.children = new HashMap<Character, TrieNode>();
    }

}